import { Component, OnInit, Input } from "@angular/core";
import { FormLayout, DValidateRules } from "ng-devui/form";
import { ManageService } from "src/app/@core/manage.service";
import { DialogService } from "ng-devui/modal";

@Component({
  selector: "app-operation-console",
  templateUrl: "./operation-console.component.html",
  styleUrls: ["./operation-console.component.scss"],
})
export class OperationConsoleComponent implements OnInit {
  @Input() data;
  @Input() collectionName;
  @Input() collectionIndex;
  @Input() close;
  @Input() closeDirectly;
  @Input() operate;
  @Input() subCollectionIndex;

  layoutDirection: FormLayout = FormLayout.Vertical;

  constructor(
    private manageService: ManageService,
    private dialogService: DialogService
  ) { }

  saleTime: Date;
  offShelfTime: Date;
  price: string;
  operateShow: string;
  isRequired: boolean;
  userId = parseInt(localStorage.getItem('userId'));

  collection = {
    subCollectionIndex: null,
    collectionIndex: null,
    collectionName: null,
    saleTime: null,
    offShelfTime: null,
    price: null,
    userId: this.userId
  };

  collectionDetail = {
    children: [],
    collectionName: null,
    saleTime: null,
    offShelfTime: null,
    price: null,
  };

  isChangeName = false;
  isChangeSaleTime = false;
  isChangeOffShelfTime = false;
  isChangePrice = false;

  calenderRange = [new Date().getFullYear(), new Date().getFullYear() + 1];
  minStartDate = new Date(new Date().getTime());
  maxStartDate = new Date(new Date().setMonth(new Date().getMonth() + 2));
  minEndDate = new Date(new Date().setMonth(new Date().getMonth()));
  maxEndDate = new Date(new Date().setMonth(new Date().getMonth() + 4));

  formRulesRequired: { [key: string]: DValidateRules } = {
    saleTimeRules: {
      validators: [
        { required: true, message: "发售开始时间不能为空" },
        {
          minTime: this.compareTime.bind(this, ["start"]),
          message: "发售开始时间应大于当前时间1分钟",
        },
      ],
      messageShowType: "text",
    },
    offShelfTimeRules: {
      validators: [
        { required: true, message: "发售结束时间不能为空" },
        {
          minTime: this.compareTime.bind(this, ["end"]),
          message: "发售时间间隔应大于5分钟",
        },
      ],
      messageShowType: "text",
    },
  };

  priceRulesRequired: { [key: string]: DValidateRules } = {
    priceRules: {
      validators: [
        { required: true, message: "价格不能为空" },
        {
          pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
          message: "请输入正确的价格，最多包含两位小数",
        },
      ],
      messageShowType: "text",
    },
  };

  formRules: { [key: string]: DValidateRules } = {
    nameRules: {
      validators: [
        { required: true, message: "集合名称不能为空" },
        { minlength: 3 },
        { maxlength: 20 },
      ],
      message: "长度为3-20位",
      messageShowType: "text",
    },
    saleTimeRules: {
      validators: [
        {
          minTime: this.compareTime.bind(this, ["start"]),
          message: "发售开始时间应大于当前时间1分钟",
        },
      ],
      messageShowType: "text",
    },
    offShelfTimeRules: {
      validators: [
        {
          minTime: this.compareTime.bind(this, ["end"]),
          message: "发售时间间隔应大于5分钟",
        },
      ],
      messageShowType: "text",
    },
    priceRules: {
      validators: [
        {
          pattern: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
          message: "请输入正确的价格，最多包含两位小数",
        },
      ],
      messageShowType: "text",
    },
  };

  checkOffShelfTime() {
    if (this.saleTime) {
      return this.offShelfTime;
    }
  }

  checkSaleTime() {
    if (this.offShelfTime) {
      return this.saleTime;
    }
  }

  compareTime(type, value) {
    if (type[0] == "start" && value) {
      return value.getTime() > new Date().getTime() + 60000;
    }

    if (type[0] == "end") {
      if (value && this.saleTime) {
        return value.getTime() > this.saleTime.getTime() + 5 * 60000;
      } else if (value || this.saleTime) {
        return false;
      } else {
        return true;
      }
    }
  }

  ngOnInit(): void {
    this.operateShow = this.operate == "修改" ? "保存" : "发布";
    this.isRequired = this.operate == "修改" ? false : true;
    var nowtime = -28800000;
    this.collection.collectionName = this.collectionName;
    this.collection.collectionIndex = this.collectionIndex;
    this.collection.subCollectionIndex = this.subCollectionIndex;
    this.manageService
      .collectionDetail(this.collectionIndex, parseInt(this.subCollectionIndex))
      .subscribe((res) => {
        if (res.code == 0 && res.data.collectionsInfo) {
          this.saleTime = res.data.collectionsInfo[0].saleTime == nowtime ? null : new Date(res.data.collectionsInfo[0].saleTime);
          this.offShelfTime = res.data.collectionsInfo[0].offShelfTime == nowtime ? null : new Date(res.data.collectionsInfo[0].offShelfTime);
          if (res.data.collectionsInfo[0].price > -1) this.price = res.data.collectionsInfo[0].price;

          this.collectionDetail.saleTime = this.saleTime;
          this.collectionDetail.offShelfTime = this.offShelfTime;
          this.collectionDetail.price = this.price;
          this.collectionDetail.collectionName = this.collectionName;
          res.data.collectionsInfo.forEach((item) => {
            this.collectionDetail.children.push({
              description: item.detail.description,
              pictureName: item.detail.name,
              author: item.issuer,
              type: item.detail.category,
              supplies: item.supplies,
              pictureUrl: item.detail.url
            })
          })
        }
      }
      );
  }

  formChangeName() {
    this.isChangeName =
      this.collectionDetail.collectionName != this.collection.collectionName
        ? true
        : false;
  }

  formChangeSaleTime() {
    this.isChangeSaleTime =
      this.collectionDetail.saleTime != this.saleTime ? true : false;
  }

  formChangeOffShelfTime() {
    this.isChangeOffShelfTime =
      this.collectionDetail.offShelfTime != this.offShelfTime ? true : false;
  }

  formChangePrice() {
    if (this.price || parseFloat(this.price) >= 0) {
      this.isChangePrice =
        this.collectionDetail.price != parseFloat(this.price) ? true : false;
    } else {
      this.isChangePrice = this.collectionDetail.price >= 0 ? true : false;
    }
  }

  formChange() {
    return (
      this.isChangeName ||
      this.isChangeOffShelfTime ||
      this.isChangePrice ||
      this.isChangeSaleTime
    );
  }

  config = {
    id: "dialog-service",
    width: "360px",
    maxHeight: "200px",
    backdropCloseable: true,
  };

  resultDialog(dialogtype?: string, title?: string, text?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: title,
      content: text,
      dialogtype: dialogtype,
      buttons: [
        {
          cssClass: "primary",
          text: "关闭",
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }

  openDialog(dialogtype?: string, title?: string, text?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: title,
      content: text,
      dialogtype: dialogtype,
      buttons: [
        {
          cssClass: "primary",
          text: "确定",
          handler: ($event: Event) => {
            if (title == "保存") {
              this.save();
            }
            if (title == "发布") {
              this.publish();
            }
            results.modalInstance.hide();
          },
        },
        {
          cssClass: "common",
          text: "关闭",
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }

  prepare() {
    if (this.offShelfTime) {
      this.collection.offShelfTime = this.offShelfTime.getTime();
    } else {
      this.collection.offShelfTime = -1;
    }
    if (this.saleTime) {
      this.collection.saleTime = this.saleTime.getTime();
    } else {
      this.collection.saleTime = -1;
    }
    if (this.price !== null) {
      this.collection.price = parseFloat(this.price);
    } else {
      this.collection.price = -1;
    }

    return this.collection;
  }

  save() {
    this.prepare();
    this.manageService.collectionModify(this.collection).subscribe((res) => {
      if (res.code == 0) {
        this.resultDialog("success", "保存成功", res.msg);
        this.closeDirectly();
      } else {
        this.resultDialog("failed", "保存失败", res.msg);
      }
    });
  }

  publish() {
    this.prepare();
    this.manageService.collectionPublish(this.collection).subscribe((res) => {
      if (res.code == 0) {
        this.openDialog("success", "发布成功", res.msg);
        this.closeDirectly();
      } else {
        this.openDialog("failed", "发布失败", res.msg);
      }
    });
  }

  submitForm({ valid, directive, data, errors }) {
    if (data == "save" && valid) {
      if (this.subCollectionIndex == 0) {
        this.openDialog("warning", "保存", "请确定是否批量保存藏品信息？");
      }
      else {
        this.openDialog("warning", "保存", "请确定是否保存藏品信息？");
      }
    }
    if (data == "cancel") {
      this.close();
    }
    if (data == "publish" && valid) {
      if (this.subCollectionIndex == 0) {
        this.openDialog("warning", "发布", "请确定是否批量发布藏品信息？");
      }
      else {
        this.openDialog("warning", "发布", "请确定是否发布藏品信息？");
      }
    }
  }
}
